<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      @click-left="onClickLeft"
      left-arrow
      title="黑马头条"
    ></van-nav-bar>

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="isLoading">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="article.title">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ article.title }}</h1>

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{ article.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ article.pubdate | relativeTime }}
          </div>
          <follow-user
            class="follow-btn"
            :is-followed="article.is_followed"
            :user-id="article.aut_id"
            @update-is_followed="article.is_followed = $event"
          />
          <!-- <van-button
            v-if="article.is_followed"
            class="follow-btn"
            round
            size="small"
            @click="onFollow"
            :loading="followLoading"
            >已关注</van-button
          >
          <van-button
            v-else
            class="follow-btn"
            type="info"
            color="#3296fa"
            round
            size="small"
            icon="plus"
            @click="onFollow"
            :loading="followLoading"
            >关注</van-button
          > -->
        </van-cell>

        <!-- 文章内容 -->
        <div
          class="article-content markdown-body"
          v-html="article.content"
          ref="article-content"
        ></div>
        <van-divider>正文结束</van-divider>
        <!-- 评论列表区域 -->
        <comment-list
          :source="article.art_id"
          :list="commentList"
          @onload-success="totalCommentCount = $event.total_count"
          :article-id="article.art_id"
          @reply-click="onReplyClick"
        />
        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button
            @click="isPostShow = true"
            class="comment-btn"
            type="default"
            round
            size="small"
            >写评论</van-button
          >
          <van-icon name="comment-o" :badge="totalCommentCount" color="#777" />
          <collect-article
            class="btn-item"
            :value="value"
            @input="iconchange"
            :article-id="article.art_id"
          ></collect-article>
          <like-article
            class="btn-item"
            :value="value1"
            @input="change"
            :article-id="article.art_id"
          />
          <van-icon name="share" color="#777777"></van-icon>
        </div>
      </div>

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="errStatus === 404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="loadArticle()"
          >点击重试</van-button
        >
      </div>
    </div>
    <!-- //底部区域下方添加 弹出层 -->
    <van-popup v-model="isPostShow" position="bottom">
      <!-- 文章评论 -->
      <comment-post
        :target="article.art_id"
        @post-success="onPostSuccess"
        :articleId="articleId"
      />
    </van-popup>
    <!-- 回复评论组件 -->
    <van-popup v-model="isReplyShow" position="bottom" style="height: 90%">
      <comment-reply
        :comment="currentComment"
        v-if="isReplyShow"
        @close="isReplyShow = false"
      />
    </van-popup>
  </div>
</template>

<script>
// 导入图片预览效果
import { ImagePreview } from 'vant'
import { getArticleById } from '@/api/article'
// import { addFollow, deleteFollow } from '@/api/user'
import FollowUser from '@/components/follow-user'
import CollectArticle from '@/components/collect-article'
import LikeArticle from '@/components/like-article'
import CommentList from './components/comment-list'
import CommentPost from './components/comment-post'
import CommentReply from './components/comment-reply'
export default {
  // 给所有的后代组件提供数据
  // 然后在任何后代组件里，我们都可以使用 inject 选项来接收指定的我们想要添加在这个实例上的属性
  // #这个是选项，与data，props同级
  provide: function () {
    return {
      articleId: this.articleId,
    }
  },
  // 组件名称
  name: 'ArticleIndex',
  // 组件参数 接收来自父组件的数据
  props: {
    articleId: {
      //进入此界面必须传递文章id
      type: [Number, String, Object],
      required: true,
    },
  },
  // 局部注册的组件
  components: {
    FollowUser,
    CollectArticle,
    LikeArticle,
    CommentList,
    CommentPost,
    CommentReply,
  },
  // 组件状态值
  data() {
    return {
      totalCommentCount: 0,
      article: {}, // 文章详情
      isLoading: true, // 加载状态
      errStatus: '', // 错误状态码
      //   followLoading: false, // 关注时加载图标
      value: false,
      value1: 0,
      isPostShow: false, // 弹出层显示
      message: '', // 绑定文本信息
      commentList: [], // 存放数据列表
      isReplyShow: false, // 回复评论弹出层
      currentComment: {}, // // 当前点击回复的评论项
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    async loadArticle() {
      try {
        // // 随机错误
        // if (Math.random() > 0.5) {
        //   return JSON.parse('error')
        // }
        // this.isLoading = true
        const { data } = await getArticleById(this.articleId)
        this.article = data.data
        // console.log(this.article)
        // 注意：数据更新后并不会同步更新页面，所以想要获取数据更新后的页面元素，需要延时处理
        setTimeout(() => {
          this.previewImg()
        }, 0)
        // console.log(this.article)
      } catch (err) {
        if (err.response && err.response.status === 404) {
          this.errStatus = 404
        }
        this.$toast('加载失败')
      }
      // 加载完成，关闭loading
      this.isLoading = false
    },
    previewImg() {
      // ['article-content']是文章内容的ref名字
      const contentEl = this.$refs['article-content']
      //   获取文章内容中所有的图片地址
      const allImg = contentEl.querySelectorAll('img')
      //   console.log(allImg)
      //   遍历所有 img 节点，给每个节点注册点击事件
      const images = []
      allImg.forEach((element, index) => {
        images.push(element.src)
        // console.log(images)
        element.onclick = () => {
          ImagePreview({
            images,
            startPosition: index,
          })
        }
      })
    },
    iconchange() {
      //   return (this.value = !value)
      this.value = !this.value
    },
    change() {
      if (this.value1 === 1) {
        this.value1 = 0
      } else {
        this.value1 = 1
      }
    },
    onClickLeft() {
      // console.log(111)
      this.$router.back()
    },
    onPostSuccess(data) {
      // 关闭弹出层
      this.isPostShow = false
      // 将发布内容显示到列表顶部
      this.commentList.unshift(data.new_obj)
    },
    onReplyClick(comment) {
      // 将子组件中传给我评论对象存储到当前组件
      this.currentComment = comment

      // 展示评论回复弹层
      this.isReplyShow = true
    },
  },
  // 以下是生命周期钩子   注：没用到的钩子请自行删除
  /**
   * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
   */
  created() {
    this.loadArticle()
  },
  /**
   * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
   * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
   */
  mounted() {},
}
</script> 

<style scoped lang="less">
@import './github-markdown.css';
/deep/ .van-icon-arrow-left {
  color: #fff;
}
/deep/ .van-icon {
  // 这样可以让子组件文章收藏的收藏图片变大
  font-size: 40px;
}
.btn-item {
  padding: 0;
}
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>